<template>
  <div class="data-integration">
    <div class="main-container">
      <div class="page-header">
        <h1 class="page-title">数据整合中心</h1>
        <p class="page-subtitle">监控和管理所有外链数据源的连接状态和同步情况</p>
      </div>

      <!-- 数据源状态卡片 -->
      <div class="data-sources-grid">
        <!-- 自动化外链系统 -->
        <div class="data-source-card">
          <div class="card-header">
            <div class="source-info">
              <div class="source-icon auto">🤖</div>
              <div class="source-details">
                <h3>自动化外链系统</h3>
                <div class="source-description">直连数据库，实时同步</div>
              </div>
            </div>
            <div class="status-indicator">
              <div class="status-dot connected"></div>
              <span class="status-text connected">已连接</span>
            </div>
          </div>
          <div class="card-content">
            <div class="connection-details">
              <!-- <div class="detail-item">
                <div class="detail-label">数据库地址</div>
                <div class="detail-value">{{ autoSource?.config.host }}:{{ autoSource?.config.port }}</div>
              </div> -->
              <div class="detail-item">
                <div class="detail-label">连接状态</div>
                <div class="detail-value">{{ autoSource?.status === 'connected' ? '正常' : '异常' }}</div>
              </div>
              <!-- <div class="detail-item">
                <div class="detail-label">延迟</div>
                <div class="detail-value">{{ autoSource?.connectionDetails.latency || 'N/A' }}</div>
              </div> -->
              <div class="detail-item">
                <div class="detail-label">同步模式</div>
                <div class="detail-value">{{ autoSource?.config.syncMode || '实时同步' }}</div>
              </div>
            </div>

            <div class="sync-stats">
              <div class="stats-title">外链数据统计</div>
              <div class="stats-grid">
                <div class="stat-item single-stat">
                  <div class="stat-number">{{ formatNumber(backlinkStats.auto_backlink_count) }}</div>
                  <div class="stat-label">自动化外链总数</div>
                </div>
              </div>
            </div>

            <div class="sync-controls">
              <!-- <button class="sync-btn primary" @click="syncData('auto')" :disabled="loading">立即同步</button> -->
              <!-- <button class="sync-btn" @click="testConnection('auto')" :disabled="loading">测试连接</button> -->
            </div>

            <div class="last-sync">
              最后同步: <span class="sync-time">{{ autoSource ? formatTime(autoSource.stats.lastSyncTime) : 'N/A' }}</span>
            </div>
          </div>
        </div>

        <!-- UGC内容发布系统 -->
        <div class="data-source-card">
          <div class="card-header">
            <div class="source-info">
              <div class="source-icon ugc">👥</div>
              <div class="source-details">
                <h3>UGC内容发布系统</h3>
                <div class="source-description">直连数据库，实时同步</div>
              </div>
            </div>
            <div class="status-indicator">
              <div class="status-dot" :class="ugcSource?.status || 'connected'"></div>
              <span class="status-text" :class="ugcSource?.status || 'connected'">
                {{ ugcSource?.status === 'connected' ? '已连接' : ugcSource?.status === 'warning' ? '连接超时' : '已断开' }}
              </span>
            </div>
          </div>
          <div class="card-content">
            <div class="connection-details">
              <!-- <div class="detail-item">
                <div class="detail-label">数据库地址</div>
                <div class="detail-value">{{ ugcSource?.config.host }}:{{ ugcSource?.config.port }}</div>
              </div> -->
              <div class="detail-item">
                <div class="detail-label">连接状态</div>
                <div class="detail-value">{{ ugcSource?.status === 'connected' ? '正常' : '异常' }}</div>
              </div>
              <!-- <div class="detail-item">
                <div class="detail-label">延迟</div>
                <div class="detail-value">{{ ugcSource?.connectionDetails.latency || 'N/A' }}</div>
              </div> -->
              <div class="detail-item">
                <div class="detail-label">同步模式</div>
                <div class="detail-value">{{ ugcSource?.config.syncMode || '实时同步' }}</div>
              </div>
            </div>

            <div class="sync-stats">
              <div class="stats-title">外链数据统计</div>
              <div class="stats-grid">
                <div class="stat-item single-stat">
                  <div class="stat-number">{{ formatNumber(backlinkStats.ugc_backlink_count) }}</div>
                  <div class="stat-label">UGC外链总数</div>
                </div>
              </div>
            </div>

            <div class="sync-controls">
              <!-- <button class="sync-btn primary" @click="syncData('ugc')" :disabled="loading">立即同步</button> -->
              <!-- <button class="sync-btn" @click="testConnection('ugc')" :disabled="loading">测试连接</button> -->
            </div>

            <div class="last-sync">
              最后同步: <span class="sync-time">{{ ugcSource ? formatTime(ugcSource.stats.lastSyncTime) : 'N/A' }}</span>
            </div>
          </div>
        </div>

        <!-- 人工采购系统 -->
        <div class="data-source-card">
          <div class="card-header">
            <div class="source-info">
              <div class="source-icon manual">📝</div>
              <div class="source-details">
                <h3>人工采购系统</h3>
                <div class="source-description">Excel模板导入(<span class="download-link"
                    @click="downloadExcel()">点击下载Excel模板</span>)，定期同步</div>
              </div>
            </div>
            <div class="status-indicator">
              <div class="status-dot" :class="manualSource?.status || 'warning'"></div>
              <span class="status-text" :class="manualSource?.status || 'warning'">
                {{ manualSource?.status === 'connected' ? '已连接' : manualSource?.status === 'warning' ? '连接超时' : '已断开' }}
              </span>
            </div>
          </div>
          <div class="card-content">
            <div class="connection-details">
              <div class="detail-item">
                <div class="detail-label">导入方式</div>
                <div class="detail-value">{{ manualSource?.connectionDetails.importMethod || 'Excel模板' }}</div>
              </div>
              <div class="detail-item">
                <div class="detail-label">连接状态</div>
                <div class="detail-value">{{ manualSource?.status === 'connected' ? '正常' : '超时' }}</div>
              </div>
              <!-- <div class="detail-item">
                <div class="detail-label">同步频率</div>
                <div class="detail-value">{{ manualSource?.config.frequency || '每4小时' }}</div>
              </div> -->
              <!-- <div class="detail-item">
                <div class="detail-label">下次同步</div>
                <div class="detail-value">{{ manualSource?.connectionDetails.nextSync || '16:00' }}</div>
              </div> -->
            </div>

            <div class="sync-stats">
              <div class="stats-title">外链数据统计</div>
              <div class="stats-grid">
                <div class="stat-item single-stat">
                  <div class="stat-number">{{ formatNumber(backlinkStats.manual_backlink_count) }}</div>
                  <div class="stat-label">人工采购外链总数</div>
                </div>
              </div>
            </div>

            <div class="sync-controls">
              <!-- <button class="sync-btn primary" @click="syncData('manual')" :disabled="loading">重新连接</button> -->
              <button class="sync-btn" @click="uploadExcel()" :disabled="loading">上传Excel</button>
            </div>

            <div class="last-sync">
              最后同步: <span class="sync-time">{{ manualSource ? formatTime(manualSource.stats.lastSyncTime) : 'N/A'
              }}</span>
            </div>
          </div>
        </div>

        <!-- PR发布系统 -->
        <div class="data-source-card">
          <div class="card-header">
            <div class="source-info">
              <div class="source-icon pr">📢</div>
              <div class="source-details">
                <h3>PR发布系统</h3>
                <div class="source-description">自动录入</div>
              </div>
            </div>
            <div class="status-indicator">
              <div class="status-dot" :class="prSource?.status || 'connected'"></div>
              <span class="status-text" :class="prSource?.status || 'connected'">
                {{ prSource?.status === 'connected' ? '已连接' : prSource?.status === 'warning' ? '连接超时' : '已断开' }}
              </span>
            </div>
          </div>
          <div class="card-content">
            <div class="connection-details">
              <div class="detail-item">
                <div class="detail-label">录入方式</div>
                <div class="detail-value">{{ prSource?.connectionDetails.importMethod || '手动+批量' }}</div>
              </div>
              <div class="detail-item">
                <div class="detail-label">连接状态</div>
                <div class="detail-value">{{ prSource?.status === 'connected' ? '正常' : '异常' }}</div>
              </div>
              <!-- <div class="detail-item">
                <div class="detail-label">同步频率</div>
                <div class="detail-value">{{ prSource?.config.frequency || '每30分钟' }}</div>
              </div> -->
              <!-- <div class="detail-item">
                <div class="detail-label">下次同步</div>
                <div class="detail-value">{{ prSource?.connectionDetails.nextSync || '15:00' }}</div>
              </div> -->
            </div>

            <div class="sync-stats">
              <div class="stats-title">外链数据统计</div>
              <div class="stats-grid">
                <div class="stat-item single-stat">
                  <div class="stat-number">{{ formatNumber(backlinkStats.pr_backlink_count) }}</div>
                  <div class="stat-label">PR发布外链总数</div>
                </div>
              </div>
            </div>

            <div class="sync-controls">
              <!-- <button class="sync-btn primary" @click="syncData('pr')" :disabled="loading">立即同步</button> -->
              <!-- <button class="sync-btn" @click="addPRRecord()" :disabled="loading">录入PR</button> -->
            </div>

            <div class="last-sync">
              最后同步: <span class="sync-time">{{ prSource ? formatTime(prSource.stats.lastSyncTime) : 'N/A' }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { api } from '../api'
import { mockApi, isMockMode } from '../api/mock'
import type { DataSource, DataSourceType } from '../api/services/dataIntegration'
import { useToast } from '../composables/useToast'
const { success, error: showError } = useToast()

// 数据状态
const dataSources = ref<DataSource[]>([])
const loading = ref(false)
const error = ref<string | null>(null)
const backlinkStats = ref({
  auto_backlink_count: 0,
  pr_backlink_count: 0,
  manual_backlink_count: 0,
  ugc_backlink_count: 0
})

let intervalId: number | null = null

// 计算各个数据源的信息
const autoSource = computed(() => dataSources.value.find(s => s.type === 'auto'))
const ugcSource = computed(() => dataSources.value.find(s => s.type === 'ugc'))
const manualSource = computed(() => dataSources.value.find(s => s.type === 'manual'))
const prSource = computed(() => dataSources.value.find(s => s.type === 'pr'))

// 获取外链统计数据 - 统一接口获取所有四个数据源的数据
const fetchBacklinkStats = async () => {
  try {
    const response = await api.data.getAutoBacklinks()
    if (response.code === 200) {
      // 更新所有四个数据源的外链统计数据
      backlinkStats.value = {
        auto_backlink_count: response.data.auto_backlink_count || 0,
        pr_backlink_count: response.data.pr_backlink_count || 0,
        manual_backlink_count: response.data.manual_backlink_count || 0,
        ugc_backlink_count: response.data.ugc_backlink_count || 0
      }
    }
  } catch (err) {
    console.error('获取外链统计数据失败:', err)
    // 如果获取失败，设置默认值
    backlinkStats.value = {
      auto_backlink_count: 0,
      pr_backlink_count: 0,
      manual_backlink_count: 0,
      ugc_backlink_count: 0
    }
  }
}

// 格式化数字显示
const formatNumber = (num: number): string => {
  return num.toLocaleString()
}

// 刷新所有数据（数据源状态 + 外链统计）
const refreshAllData = async () => {
  await Promise.all([
    fetchDataSources(), // 这个函数内部已经包含了 fetchBacklinkStats()
  ])
}

// 获取数据源列表和外链统计数据
const fetchDataSources = async () => {
  try {
    loading.value = true
    error.value = null

    // 并行获取数据源信息和外链统计数据
    const [sourcesResponse] = await Promise.all([
      isMockMode
        ? mockApi.dataIntegration.getSources()
        : api.dataIntegration.getSources(),
      fetchBacklinkStats() // 使用统一接口获取所有外链数据
    ])

    dataSources.value = sourcesResponse.data
  } catch (err) {
    error.value = err instanceof Error ? err.message : '获取数据源失败'
    console.error('获取数据源失败:', err)
  } finally {
    loading.value = false
  }
}

// 格式化时间
const formatTime = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 同步数据
const syncData = async (sourceType: DataSourceType) => {
  const sourceNames: Record<string, string> = {
    'auto': '自动化外链系统',
    'ugc': 'UGC内容发布系统',
    'manual': '人工采购系统',
    'pr': 'PR发布系统'
  }

  try {
    loading.value = true

    // 使用统一的同步接口
    const response = await api.data.syncData()
    if (response.code === 200) {
      alert(`${sourceNames[sourceType]} 同步成功！\n\n${response.data}`)
      // 刷新所有数据（包括外链统计和数据源状态）
      await refreshAllData()
    }
  } catch (err) {
    const message = err instanceof Error ? err.message : '同步失败'
    alert(`${sourceNames[sourceType]} 同步失败：${message}`)
  } finally {
    loading.value = false
  }
}

// 测试连接
const testConnection = async (sourceType: DataSourceType) => {
  try {
    loading.value = true

    const response = isMockMode
      ? await mockApi.dataIntegration.testConnection(sourceType)
      : await api.dataIntegration.testConnection(sourceType)

    const result = response.data
    const status = result.success ? '✅ 连接成功' : '❌ 连接失败'
    const details = `
网络连通性: ${result.details.network ? '✅' : '❌'}
身份验证: ${result.details.authentication ? '✅' : '❌'}
数据库访问: ${result.details.database ? '✅' : '❌'}
权限检查: ${result.details.permissions ? '✅' : '❌'}
延迟: ${result.latency}ms`

    alert(`连接测试结果\n\n${status}\n${result.message}\n\n详细信息:${details}`)
  } catch (err) {
    const message = err instanceof Error ? err.message : '测试连接失败'
    alert(`连接测试失败：${message}`)
  } finally {
    loading.value = false
  }
}

// 上传Excel
const uploadExcel = () => {
  // 创建文件输入元素
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = '.xlsx,.xls'
  input.onchange = async (e) => {
    const file = (e.target as HTMLInputElement).files?.[0]
    if (!file) return

    try {
      loading.value = true

      const response = await api.data.uploadExcel(file)

      success('Excel上传成功', `处理记录数: ${response.data.recordCount}\n${response.data.message}`)

      // 刷新所有数据
      await refreshAllData()
    } catch (err) {
      const message = err instanceof Error ? err.message : '上传失败'
      showError('Excel上传失败', message)
    } finally {
      loading.value = false
    }
  }
  input.click()
}

// 下载Excel模板
const downloadExcel = async () => {
  try {
    loading.value = true
    await api.data.downloadExcelTemplate()
    success('Excel模板下载成功')
  } catch (err) {
    console.error('Excel模板下载失败:', err)
    const message = err instanceof Error ? err.message : '下载失败'
    showError('Excel模板下载失败', message)
  } finally {
    loading.value = false
  }
}

// 添加PR记录
const addPRRecord = () => {
  // 这里可以打开一个模态框或跳转到PR录入页面
  alert('打开PR记录录入界面\n\n录入内容：\n- PR文章URL\n- 外链URL\n- 发布平台\n- 质量指标')
}

// 初始化数据
onMounted(async () => {
  await refreshAllData()

  // 设置定时刷新 - 定期更新所有数据
  intervalId = window.setInterval(async () => {
    await refreshAllData()
  }, 30000) // 每30秒刷新一次
})

onUnmounted(() => {
  if (intervalId) {
    clearInterval(intervalId)
  }
})
</script>
<style s coped>
.data-integration {
  background: #f8fafc;
  min-height: 100vh;
}

.main-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 30px;
}

.page-header {
  margin-bottom: 30px;
}

.page-title {
  font-size: 28px;
  font-weight: 700;
  color: #1a202c;
  margin-bottom: 10px;
}

.page-subtitle {
  color: #718096;
  font-size: 16px;
}

.data-sources-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 25px;
  margin-bottom: 40px;
}

.data-source-card {
  background: white;
  border-radius: 15px;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  transition: all 0.3s ease;
}

.data-source-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.12);
}

.card-header {
  padding: 25px;
  border-bottom: 2px solid #f7fafc;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.source-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.source-icon {
  width: 50px;
  height: 50px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: white;
}

.source-icon.auto {
  background: linear-gradient(135deg, #4299e1, #3182ce);
}

.source-icon.ugc {
  background: linear-gradient(135deg, #48bb78, #38a169);
}

.source-icon.manual {
  background: linear-gradient(135deg, #ed8936, #dd6b20);
}

.source-icon.pr {
  background: linear-gradient(135deg, #9f7aea, #805ad5);
}

.source-details h3 {
  font-size: 18px;
  font-weight: 600;
  color: #2d3748;
  margin-bottom: 5px;
}

.source-description {
  font-size: 14px;
  color: #718096;
}

.status-indicator {
  display: flex;
  align-items: center;
  gap: 8px;
}

.status-dot {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  animation: pulse 2s infinite;
}

.status-dot.connected {
  background: #48bb78;
}

.status-dot.disconnected {
  background: #f56565;
}

.status-dot.warning {
  background: #ed8936;
}

@keyframes pulse {
  0% {
    opacity: 1;
  }

  50% {
    opacity: 0.5;
  }

  100% {
    opacity: 1;
  }
}

.status-text {
  font-size: 14px;
  font-weight: 600;
}

.status-text.connected {
  color: #22543d;
}

.status-text.disconnected {
  color: #c53030;
}

.status-text.warning {
  color: #c05621;
}

.card-content {
  padding: 25px;
}

.connection-details {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 25px;
}

.detail-item {
  display: flex;
  flex-direction: column;
}

.detail-label {
  font-size: 12px;
  color: #a0aec0;
  margin-bottom: 5px;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.detail-value {
  font-size: 14px;
  font-weight: 600;
  color: #2d3748;
}

.sync-stats {
  background: #f8fafc;
  border-radius: 10px;
  padding: 20px;
  margin-bottom: 20px;
}

.stats-title {
  font-size: 14px;
  font-weight: 600;
  color: #4a5568;
  margin-bottom: 15px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
}

.stat-item {
  text-align: center;
}

.stat-item.single-stat {
  grid-column: 1 / -1;
}

.stat-number {
  font-size: 20px;
  font-weight: 700;
  color: #2d3748;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 12px;
  color: #718096;
}

.sync-controls {
  display: flex;
  gap: 10px;
}

.sync-btn {
  flex: 1;
  padding: 10px 15px;
  border: 2px solid #e2e8f0;
  border-radius: 8px;
  background: white;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.sync-btn:hover {
  border-color: #667eea;
  color: #667eea;
}

.sync-btn.primary {
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  border-color: transparent;
}

.sync-btn.primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(102, 126, 234, 0.3);
}

.sync-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none !important;
  box-shadow: none !important;
}

.sync-btn:disabled:hover {
  border-color: #e2e8f0;
  color: inherit;
}

.last-sync {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #e2e8f0;
  font-size: 13px;
  color: #718096;
  text-align: center;
}

.sync-time {
  font-weight: 600;
  color: #4a5568;
}

.download-link {
  color: #3182ce;
  text-decoration: underline;
  cursor: pointer;
  font-weight: 600;
  transition: all 0.2s ease;
}

.download-link:hover {
  color: #2c5aa0;
  text-decoration: none;
  background-color: rgba(49, 130, 206, 0.1);
  padding: 2px 4px;
  border-radius: 4px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .data-sources-grid {
    grid-template-columns: 1fr;
  }

  .connection-details {
    grid-template-columns: 1fr;
  }

  .main-container {
    padding: 20px;
  }
}
</style>